import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
    {
        path: '/',
        redirect: '/index'
    }, {
        path: '/index',
        name: 'index',
        meta: {
            title: '欢迎参加我们的婚礼'
        },
        component: () => import('src/pages/index')
    }, {
        path: '/send',
        name: 'send',
        meta: {
            title: ''
        },
        component: () => import('src/pages/send')
    }, {
        path: '/login',
        name: 'login',
        meta: {
            title: '登录'
        },
        component: () => import('src/pages/login')
    }
];

const router = new VueRouter({
    routes: routes,
    mode: "history"
});

router.beforeEach((to, from, next) => {
    if (to.name === 'login') {
        next();
    } else {
        const token = localStorage.getItem("token");
        if (token) {
            let jwtToken = token.split('.');
            let data = JSON.parse(atob(jwtToken[1]));
            if (data.exp * 1000 > new Date().getTime()) {
                next();
            } else {
                localStorage.removeItem("token");
                next({
                    path: '/login',
                    query: {
                        from: to.path
                    }
                });
            }
        } else {
            next({
                path: '/login',
                query: {
                    from: to.path
                }
            });
        }
    }
});

router.afterEach((to, from) => {
    if (to.meta.title) {
        document.title = to.meta.title;
    }
    window.scrollTo(0, 0);
});
export default router;
